package com.songcha.library_base.mvvm.base

import android.os.Bundle
import androidx.databinding.ViewDataBinding
import androidx.recyclerview.widget.RecyclerView
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.songcha.library_base.interfaces.IRefreshData
import com.scwang.smart.refresh.layout.SmartRefreshLayout

abstract class BaseRefreshMvvmActivity<VM:BaseRefreshViewModel<out BaseRepository,out Any>,DB:ViewDataBinding>:BaseMvvmActivity<VM,DB> (),
    IRefreshData {
    protected var srl:SmartRefreshLayout?=null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        srl=getRefreshLayout()?.apply {
            setEnableLoadMore(false)
            setOnRefreshListener {
                viewModel.onRefreshing()
                onGetData()
            }
        }
    }


    override fun initView(savedInstanceState: Bundle?) {
        super.initView(savedInstanceState)
        viewModel.refresh_state.observe(this){
            when(it){
                BaseRefreshViewModel.RefreshStateVM.REFRESHING->onRefreshing()
                BaseRefreshViewModel.RefreshStateVM.REFRESH_SUCCESS->onRefreshSuccess()
                BaseRefreshViewModel.RefreshStateVM.REFRESH_ERROR->onRefreshError(viewModel.refresh_error!!)
                BaseRefreshViewModel.RefreshStateVM.REFRESH_NO_NETWORK->onRefreshNoNetwork()
                BaseRefreshViewModel.RefreshStateVM.REFRESH_CONNECT_ERROR->onRefreshConnectError()
                BaseRefreshViewModel.RefreshStateVM.REFRESH_NO_DATA->onRefreshNoData()
                BaseRefreshViewModel.RefreshStateVM.REFRESH_TIMEOUT->onRefreshTimeOut()
            }
        }

        addRlstObserve()
    }

    protected open fun addRlstObserve(){
        //need reset adapter when refreshing,cannot update automatically
        viewModel!!.rlst.observe(this){
            if(it!=null && it.size>0){
                initListData()
            }
        }
    }

    abstract fun initListData()

    abstract fun getRefreshLayout():SmartRefreshLayout

    abstract fun getListAdapter():RecyclerView.Adapter<BaseViewHolder>?

    override fun onRefreshing() {

    }

    override fun onRefreshSuccess() {
        srl?.finishRefresh(true)
        getListAdapter()?.notifyDataSetChanged()
    }

    override fun onRefreshError(e: Throwable) {
        srl?.finishRefresh(false)
    }

    override fun onRefreshNoData() {
        srl?.finishRefresh(false)
    }

    override fun onRefreshNoNetwork() {
        srl?.finishRefresh(false)
    }

    override fun onRefreshConnectError() {
        srl?.finishRefresh(false)
    }

    override fun onRefreshTimeOut() {
        srl?.finishRefresh(false)
    }

}